package com.bingxu.flink.timer;

import com.bingxu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author :BingXu
 * @description :TODO
 * @date :2021/8/17 20:09
 * @modifier :
 */

public class ProcessTimer {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",10086);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        // 设置水印自动抛出的时间周期
        env.getConfig().setAutoWatermarkInterval(1000);

        env
                .socketTextStream("localhost", 9999)
                .map((MapFunction<String, WaterSensor>) value -> {
                    String[] fields = value.split(",");
                    return new WaterSensor(fields[0], Long.parseLong(fields[1]) * 1000, Integer.valueOf(fields[2]));
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private long time;

                    /**
                     * 设置定时器，定时器为处理时间5S后触发，5S触发后进行相应的操作处理
                     *
                     * @param value 传入元素的值
                     * @param ctx 上下文对象
                     * @param out 输出处理对象
                     * @throws Exception
                     */
                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        time = ctx.timerService().currentProcessingTime() + 5000;
                        ctx.timerService().registerProcessingTimeTimer(time);
                        out.collect(value.toString()+time);
                    }

                    /**
                     * 处理定时器触发的操作
                     * @param timestamp 定时器的时间
                     * @param ctx 上下文对象
                     * @param out 输出对象
                     * @throws Exception
                     */
                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        System.out.println("timestamp = " + timestamp);
                        out.collect("处理定时器5S的逻辑操作");
                    }
                }).print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
